using rpc_service.config;
using rpc_service.log;
using Microsoft.Extensions.Logging;

namespace rpc_service.core.registry;

public class RegistryManager
{
    private static readonly ILogger _logger = Logger.GetLoggerFactory().CreateLogger<RegistryManager>();
    private static readonly List<RegistryFactory> _factories = new List<RegistryFactory>();
    
    static RegistryManager()
    {
        // 注册所有工厂实现
        RegisterFactory(new ConsulRegistryFactory());
    }
    
    public static void RegisterFactory(RegistryFactory factory)
    {
        _factories.Add(factory);
    }
    
    public static Registry GetRegistry(Config config)
    {
        if (string.IsNullOrEmpty(config.Registry))
        {
            _logger.LogWarning("No registry type specified in configuration");
            return null;
        }
        
        foreach (var factory in _factories)
        {
            if (factory.Supports(config.Registry))
            {
                var registry = factory.CreateRegistry(config);
                if (registry != null)
                {
                    return registry;
                }
            }
        }
        
        _logger.LogError($"No registry factory found for type: {config.Registry}");
        return null;
    }
    
    public static Type GetRegistryType(Config config)
    {
        if (string.IsNullOrEmpty(config.Registry))
        {
            _logger.LogWarning("No registry type specified in configuration");
            return null;
        }
        
        foreach (var factory in _factories)
        {
            if (factory.Supports(config.Registry))
            {
                var registryType = factory.GetRegistryType(config);
                if (registryType != null)
                {
                    return registryType;
                }
            }
        }
        
        _logger.LogError($"No registry factory found for type: {config.Registry}");
        return null;
    }
}